// 状态映射
const statusMap = {
    'intact': { text: '基本完好', class: 'status-intact', value: 1 },
    'damaged': { text: '损坏', class: 'status-damaged', value: 2 },
    'collapsed': { text: '倒塌', class: 'status-collapsed', value: 3 }
};

// 建筑物数据
let buildingData = null;
let statusHistory = [];
let earthquakeEvents = [];

// 初始化页面
async function initPage() {
    // 获取建筑物数据
    try {
        buildingData = JSON.parse(sessionStorage.getItem('selectedBuilding'));
    } catch (e) {
        console.error("解析建筑物数据失败:", e);
    }
    
    // 如果没有数据，返回地图页
    if (!buildingData) {
        alert("未找到建筑物数据，正在返回地图页面");
        window.location.href = 'index.html';
        return;
    }
    
    // 加载地震事件数据
    await loadEarthquakeEvents();
    
    // 加载建筑物状态历史数据
    await loadStatusHistory();
    
    // 设置建筑物基本信息
    setBuildingInfo();
    
    // 生成时间线
    generateTimeline();
    
    // 生成图表
    generateChart();
    
    // 加载损坏照片
    loadDamagePhotos();
    
    // 返回按钮事件
    document.getElementById('back-btn').addEventListener('click', function() {
        window.location.href = 'index.html';
    });
}

// 加载地震事件数据
async function loadEarthquakeEvents() {
    try {
        // 修改路径指向data文件夹
        const response = await fetch('data/earthquake-events.json');
        const data = await response.json();
        earthquakeEvents = data.events;
    } catch (error) {
        console.error('加载地震事件数据失败:', error);
        // 使用备用数据
        earthquakeEvents = [
            { id: "EQ001", magnitude: 8.0, time: "2023-05-12T14:28:00Z", phase: "主震" },
            { id: "EQ002", magnitude: 6.5, time: "2023-05-12T15:05:00Z", phase: "第一次强余震" },
            { id: "EQ008", magnitude: 4.0, time: "2023-05-13T03:40:00Z", phase: "第二次强余震" }
        ];
    }
}

// 加载建筑物状态历史数据
async function loadStatusHistory() {
    try {
        // 修改路径指向data文件夹
        const dayFiles = [
            'data/disaster-data-day1.json',
            'data/disaster-data-day2.json',
            'data/disaster-data-day3.json',
            'data/disaster-data-day4.json',
            'data/disaster-data-day5.json',
            'data/disaster-data-day6.json',
            'data/disaster-data-day7.json',
            'data/disaster-data-day8.json',
            'data/disaster-data-day9.json',
            'data/disaster-data-day10.json',
            'data/disaster-data-day11.json',
            'data/disaster-data-day12.json',
            'data/disaster-data-day13.json',
            'data/disaster-data-day14.json'
        ];
        
        const buildingId = buildingData.properties?.id || 'B001';
        
        // 加载所有天的数据
        for (const file of dayFiles) {
            try {
                const response = await fetch(file);
                const data = await response.json();
                
                // 提取当前建筑物的状态变化
                for (const timelineItem of data.timeline) {
                    for (const feature of timelineItem.features) {
                        if (feature.properties.id === buildingId) {
                            const dateObj = new Date(timelineItem.time);
                            const formattedDate = `${dateObj.toLocaleDateString()} ${dateObj.toLocaleTimeString()}`;
                            
                            // 查找相关地震事件
                            const relatedEarthquake = earthquakeEvents.find(eq => {
                                const eqTime = new Date(eq.time).getTime();
                                const statusTime = new Date(timelineItem.time).getTime();
                                return Math.abs(eqTime - statusTime) < 3600000; // 1小时内
                            });
                            
                            let description = '';
                            if (relatedEarthquake) {
                                description = `${relatedEarthquake.phase}导致建筑物状态变化`;
                            } else {
                                description = '建筑物状态更新';
                            }
                            
                            statusHistory.push({
                                time: timelineItem.time,
                                date: formattedDate,
                                status: feature.status,
                                description: description,
                                earthquake: relatedEarthquake
                            });
                        }
                    }
                }
            } catch (error) {
                console.error(`加载${file}失败:`, error);
            }
        }
        
        // 按时间排序
        statusHistory.sort((a, b) => new Date(a.time) - new Date(b.time));
        
    } catch (error) {
        console.error('加载状态历史数据失败:', error);
        // 使用备用数据
        statusHistory = [
            { time: "2023-05-12T14:28:00Z", date: "2023-05-12 14:28", status: "intact", description: "主震发生，建筑物基本完好" },
            { time: "2023-05-12T15:05:00Z", date: "2023-05-12 15:05", status: "damaged", description: "第一次强余震导致建筑物损坏" },
            { time: "2023-05-13T03:40:00Z", date: "2023-05-13 03:40", status: "collapsed", description: "第二次强余震导致建筑物倒塌" }
        ];
    }
}

// 设置建筑物基本信息
function setBuildingInfo() {
    const properties = buildingData.properties || {};
    
    document.getElementById('building-name').textContent = properties.name || '未知建筑物';
    document.getElementById('building-type').textContent = properties.type_detail || '未知类型';
    document.getElementById('damage-level').textContent = properties.damage || '未知';
    document.getElementById('risk-level').textContent = properties.risk || '未知';
    document.getElementById('impact-area').textContent = properties.area ? `${properties.area} m²` : '未知';
    document.getElementById('building-year').textContent = properties.year || '未知';
    document.getElementById('structure-type').textContent = properties.structure_type || '未知';
    
    if (buildingData.coordinates && buildingData.coordinates.length >= 2) {
        document.getElementById('building-coords').textContent = 
            `${buildingData.coordinates[0].toFixed(4)}°E, ${buildingData.coordinates[1].toFixed(4)}°N`;
    }
    
    // 设置当前状态
    const currentStatus = buildingData.status || 'intact';
    const statusElement = document.getElementById('current-status');
    statusElement.textContent = statusMap[currentStatus].text;
    statusElement.className = 'status-badge ' + statusMap[currentStatus].class;
}

// 生成时间线
function generateTimeline() {
    const timeline = document.getElementById('status-timeline');
    timeline.innerHTML = '';
    
    if (statusHistory.length === 0) {
        timeline.innerHTML = '<div class="photo-placeholder">暂无状态历史数据</div>';
        return;
    }
    
    statusHistory.forEach((item, index) => {
        const timelineItem = document.createElement('div');
        timelineItem.className = 'timeline-item';
        
        const statusInfo = statusMap[item.status];
        
        timelineItem.innerHTML = `
            <div class="timeline-content">
                <div class="timeline-date">${item.date}</div>
                <p>${item.description}</p>
                <span class="timeline-status ${statusInfo.class}">${statusInfo.text}</span>
                ${item.earthquake ? `
                    <div class="earthquake-info">
                        关联地震: ${item.earthquake.phase} (${item.earthquake.magnitude}级)
                    </div>
                ` : ''}
            </div>
        `;
        
        timeline.appendChild(timelineItem);
    });
}

// 生成状态变化图表
function generateChart() {
    const ctx = document.getElementById('status-chart');
    if (!ctx) return;
    
    // 准备图表数据
    const dates = statusHistory.map(item => item.date);
    const statusValues = statusHistory.map(item => statusMap[item.status].value);
    
    // 创建图表
    new Chart(ctx, {
        type: 'line',
        data: {
            labels: dates,
            datasets: [{
                label: '建筑物状态',
                data: statusValues,
                borderColor: '#FF9F55',
                backgroundColor: 'rgba(255, 159, 85, 0.2)',
                tension: 0.3,
                pointBackgroundColor: function(context) {
                    const index = context.dataIndex;
                    const status = statusHistory[index].status;
                    return status === 'intact' ? '#00FF00' : 
                           status === 'damaged' ? '#FFFF00' : '#FF0000';
                },
                pointBorderColor: '#fff',
                pointRadius: 6,
                pointHoverRadius: 8
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true,
                    max: 3.5,
                    ticks: {
                        stepSize: 1,
                        callback: function(value) {
                            switch(value) {
                                case 1: return '基本完好';
                                case 2: return '损坏';
                                case 3: return '倒塌';
                                default: return '';
                            }
                        }
                    },
                    grid: {
                        color: 'rgba(255, 255, 255, 0.1)'
                    }
                },
                x: {
                    grid: {
                        color: 'rgba(255, 255, 255, 0.1)'
                    },
                    ticks: {
                        maxRotation: 45,
                        minRotation: 45
                    }
                }
            },
            plugins: {
                legend: {
                    labels: {
                        color: '#fff'
                    }
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            const index = context.dataIndex;
                            let status = '';
                            switch(context.parsed.y) {
                                case 1: status = '基本完好'; break;
                                case 2: status = '损坏'; break;
                                case 3: status = '倒塌'; break;
                            }
                            return `${statusHistory[index].time.split('T')[0]}: ${status}`;
                        }
                    }
                }
            }
        }
    });
}

// 加载损坏照片
function loadDamagePhotos() {
    const photosContainer = document.getElementById('photos-container');
    if (!photosContainer) return;
    
    // 模拟照片数据 - 实际应用中应从服务器获取
    const buildingId = buildingData.properties?.id || 'B001';
    let photos = [];
    
    if (buildingId === 'B001') {
        photos = [
            { url: 'https://placehold.co/600x400/333333/FFFFFF/png?text=轻微裂缝', caption: '主震后的裂缝' },
            { url: 'https://placehold.co/600x400/333333/FFFFFF/png?text=结构损坏', caption: '结构损坏情况' },
            { url: 'https://placehold.co/600x400/333333/FFFFFF/png?text=完全坍塌', caption: '完全坍塌状态' }
        ];
    } else {
        photos = [
            { url: 'https://placehold.co/600x400/333333/FFFFFF/png?text=损坏情况', caption: '建筑物损坏情况' }
        ];
    }
    
    // 清空容器
    photosContainer.innerHTML = '';
    
    // 如果没有照片数据
    if (photos.length === 0) {
        photosContainer.innerHTML = '<div class="photo-placeholder">暂无照片数据</div>';
        return;
    }
    
    // 添加照片
    photos.forEach(photo => {
        const photoItem = document.createElement('div');
        photoItem.className = 'photo-item';
        
        photoItem.innerHTML = `
            <img src="${photo.url}" alt="${photo.caption}" class="photo-image">
            <div class="photo-caption">${photo.caption}</div>
        `;
        
        photosContainer.appendChild(photoItem);
    });
}

// 页面加载完成后初始化
window.onload = initPage;